package thread;


import java.util.PriorityQueue;
import java.util.Timer;

// 计时器的自己实现 MyTimer —————— 三遍
class MyTimerTask implements Comparable<MyTimerTask>{
    // 优先队列里的泛型对象
    // 来实现run方法
    private Runnable runnable = null;
    // 时间
    private long time = 0;

    public long getTime(){
        return time;
    }
    public MyTimerTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public void run(){
        runnable.run();
    }
    // 因为要实现优先队列所以需要比较方法
    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}
class MyTimer{
    Thread t = null;
    private Object locker = new Object();
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
            MyTimerTask task = new MyTimerTask(runnable,delay);
            queue.offer(task);
            locker.notify();
        }
    }
    public MyTimer(){
        t = new Thread(() -> {
           while(true){
               synchronized (locker){
                   try {
                       while(queue.isEmpty()){
                           locker.wait();
                       }
                       long curTime = System.currentTimeMillis();
                       MyTimerTask task = queue.peek();

                       if(task.getTime() <= curTime){
                           queue.poll();
                           task.run();
                       } else {
                           locker.wait(task.getTime() - curTime);
                       }
                   } catch (InterruptedException e){
                       e.printStackTrace();
                   }
               }
           }
        });
        t.start();
    }
}

public class ThreadDemo24 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
        System.out.println("hello main");
    }
}
